package com.sso.ssologin.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
//import org.thymeleaf.util.StringUtils;

import com.sso.ssologin.Pojo.User;
import com.sso.ssologin.utils.LoginCacheUtil;

@Controller
// 页面跳转逻辑
@RequestMapping("/view")
public class ViewController {
    @GetMapping("/login")
    /**
     * 跳转到登录页面
     * 接收target参数，如果target参数不存在就default为空
     * 如果为空就给system1的默认值
     * @return
     */
    // @RequestParam(required = false, defaultValue = "") String target,HttpSession session
    public String toLogin(@RequestParam(required = false, defaultValue = "") String target,HttpSession session,@CookieValue(required = false,value = "TOKEN") Cookie cookie){
        System.out.println("=============="+target);  
        
        if(StringUtils.isEmpty(target)){
            target="http://homepage.sso.com:8083/view/homepage";
            //target = "http://login.sso.com:8080";
        }
        //如果是已经登陆过的用户再次访问登录系统时，就要重新定向
        
        if(cookie != null){
            String value = cookie.getValue();
            User user = LoginCacheUtil.loginUser.get(value);
            if(user != null){
                return "redirect:" + target;
            }
        }
        // 重定向地址
        session.setAttribute("target",target);
        return "login";
    }

    @GetMapping("/logout")
    public String loginOut(@CookieValue(value = "TOKEN") Cookie cookie,  HttpServletResponse response,HttpServletRequest request) {
        cookie.setMaxAge(0);
        LoginCacheUtil.loginUser.remove(cookie.getValue());
        Cookie[] cookies = request.getCookies();  
            if (null==cookies) {  
                // System.out.println("没有cookie==============");  
            } else {  
                for(Cookie cook : cookies){  
                    if(cook.getName().equals("TOKEN")){  
                        cook.setValue(null);  
                        cook.setMaxAge(0);// 立即销毁cookie  
                        cook.setPath("/");  
                        // System.out.println("被删除的cookie名字为:"+cook.getName());  
                        response.addCookie(cook);  
                        break;  
                    }  
                }  
            }  
        return "login";
    }
}
